﻿using System;
using System.IO;
using Seagull.Configuration;
using Seagull.Events;
using Seagull.Events.Drive;
using Seagull.Model.Alerts;

namespace Seagull.DAL.DriveManagers
{
    public class LocalDriveManager : DriveManagerBase
    {
        #region Singleton

        private static readonly Lazy<LocalDriveManager> _instance =
            new Lazy<LocalDriveManager>(() => new LocalDriveManager());

        public static LocalDriveManager Instance
        {
            get { return _instance.Value; }
        }

        #endregion

        private readonly Lazy<DriveInfo> _drive;

        private LocalDriveManager() :
            base(Config.Instance.DiskSpaceMonitorConfig.LocalDiskFreeSpaceQuotaGB)
        {
            _drive = new Lazy<DriveInfo>(() => 
                new DriveInfo(Config.Instance.DiskSpaceMonitorConfig.LocalDiskMonitorDrive));
        }

        public override DriveInfo Drive
        {
            get { return _drive.Value; }
        }

        protected override void OnDriveSpaceChanged(int usedPercentage)
        {
            base.OnDriveSpaceChanged(usedPercentage);
            LocalDriveSpaceChangedEvent.Instance.Publish(usedPercentage);
        }

        protected override void OnDiskFull(long freeSpaceMB)
        {
            base.OnDiskFull(freeSpaceMB);
            AlertEvent.Instance.Publish(
                    new LocalDiskFullAlert(
                        Config.Instance.DiskSpaceMonitorConfig.LocalDiskMonitorDrive,
                        (int)freeSpaceMB));
        }

        protected override void OnGetUsedPercentageError(IOException exception)
        {
            base.OnGetUsedPercentageError(exception);
            AlertEvent.Instance.Publish(new ApplicationAlert(exception, "检查本地磁盘使用量"));
        }
    }
}